﻿using CefSharp;
using CefSharp.Wpf;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Web;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace WpfApp
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private static bool InitCef = false;
        ChromiumWebBrowser Browser = null;
        string appStartupPath = System.IO.Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
        public MainWindow()
        {
            InitializeComponent();
            InitBrowser();
            comboBox.SelectedIndex = 0;
        }

        private void InitBrowser()
        {
            if (!InitCef)
            {
                CefSettings settings = new CefSettings();
                // 开启chrome的媒体流，播放视频可能会用到
                settings.CefCommandLineArgs.Add("enable-media-stream", "1");
                // 代理
                settings.CefCommandLineArgs.Add("no-proxy-server", "1");
                settings.CefCommandLineArgs.Add("proxy-server", "ProxyAddress");
                // 允许Chrom浏览器跨域，允许打开本地页面及跨域请求
                settings.CefCommandLineArgs.Add("--disable-web-security", "");
                // 用户配置文件路径，不晓得有啥用
                // settings.CefCommandLineArgs.Add("--user-data-dir", string.Format(@"{0}\config", appStartupPath));
                // 缓存路径
                settings.CachePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData), "CefSharp\\Cache");
                // 绑定setting对象
                Cef.Initialize(settings, performDependencyCheck: true, browserProcessHandler: null);
                // 进程启动时设置High-DPI为启用状态，可以理解为画面显示更精致了，低版本win系统设置这个没有啥用
                Cef.EnableHighDPISupport();
                InitCef = true;
            }
            // 初始化浏览器对象
            Browser = new ChromiumWebBrowser();
            Browser.KeyboardHandler = new KeyBoardHander();
            // 注册js对象
            Browser.JavascriptObjectRepository.Settings.LegacyBindingEnabled = true;
            CefSharpSettings.WcfEnabled = true;
            // 浏览器界面加入窗口
            browserCard.Children.Clear();
            browserCard.Children.Add(Browser);
            ChartCtrl.BoundBrowser(Browser);
        }
        #region 监听键盘事件
        private class KeyBoardHander : IKeyboardHandler
        {
            public bool OnKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey)
            {
                return false;
            }

            public bool OnPreKeyEvent(IWebBrowser browserControl, IBrowser browser, KeyType type, int windowsKeyCode, int nativeKeyCode, CefEventFlags modifiers, bool isSystemKey, ref bool isKeyboardShortcut)
            {
                if (type != KeyType.RawKeyDown) return false;
                const int VK_F5 = 0x74;
                const int VK_F12 = 0x7B;
                Console.WriteLine("{0:x4}", windowsKeyCode);
                if (windowsKeyCode == VK_F5)
                {
                    browser.Reload(); //此处可以添加想要实现的代码段
                }
                if (windowsKeyCode == VK_F12)
                {
                    browser.ShowDevTools(); ; //此处可以添加想要实现的代码段
                }
                return false;
            }
        }
        #endregion
        // 更换页面
        public void ChangePage(string indexpage)
        {
            if (!File.Exists(indexpage))
            {
                MessageBox.Show("程序将要退出，本地网页文件不错在：" + indexpage);
                return;
            }
            // url字符转义，indexpage存放本地的网页路径
            indexpage = indexpage.Replace(" ", "%20");
            string[] ss = indexpage.Split('\\');
            // 解析为浏览器地址栏能够识别的地址，如果路径出现一些特殊字符可能导致无法解析
            for (int i = 1; i < ss.Length; i++)
            {
                ss[i] = HttpUtility.UrlEncode(ss[i]);
            }
            indexpage = string.Join("\\", ss);
            // 打开路径
            Browser.LoadUrl(indexpage);
        }

        // 执行js脚本
        public void ExecuteJavaScriptAsync(string js)
        {
            if (Browser.IsBrowserInitialized)
                Browser.GetBrowser().MainFrame.ExecuteJavaScriptAsync(js);
            else
                Browser.FrameLoadEnd += new EventHandler<FrameLoadEndEventArgs>((s, e) =>
                {
                    Browser.GetBrowser().MainFrame.ExecuteJavaScriptAsync(js);
                });
        }
      
        private void ReLoadClick(object sender, RoutedEventArgs e)
        {
            Browser.Reload(true);
        }

        private void ConsoleClick(object sender, RoutedEventArgs e)
        {
            if (Browser != null)
                Browser.ShowDevTools();
            else
                MessageBox.Show("浏览器暂未加载...");
        }

        private void ComboBox_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            switch (comboBox.SelectedIndex)
            {
                case 0:
                    ChangePage(string.Format(@"{0}\WebPage\innermodel\index.html", appStartupPath));
                    break;
                case 1:
                    ChangePage(string.Format(@"{0}\WebPage\innerChart2\index.html", appStartupPath));
                    break;
            }
        }
    }
}
